local Timer = require("utils.Timer")
local cprule = require("utils.cprule")

local TableView = class("TableView",function()
	return display.newNode()
end)

local mSelf
local player
local cardnum 
function TableView:destory()
   if mSelf.clockId then
        Timer:kill(mSelf.clockId)
  end
  cardnum = nil
  player = nil
  mSelf = nil
  -- Timer = nil
end

function TableView:ctor(socket,args)
self:setTouchEnabled(true)
cardnum = 22
player = {}
player.gameStart=false
local gameBg= display.newSprite("game_bg.png",display.cx,display.cy)
gameBg:setScaleX(display.width/gameBg:getContentSize().width)
gameBg:setScaleY(display.height/gameBg:getContentSize().height)
gameBg:addTo(self)

   socketEvent  = socket
    if not args.user then
        local num = 1
        socketEvent.onroom = function ( args )
        if args.cmd == 0 then
             print("join",args.userid)
             dump(args)
             mSelf.user = args.user
             mSelf:userInit()
            num= num+1
            if num == 3 then 
                mSelf:gameStart()
            end
        elseif args.cmd ==1 then
            print("leave",args.userid)
        end
        end
    else 
        socketEvent.onroom = function ( args )
            if args.cmd == 0 then
                 print("join1111",args.userid)
                 mSelf.user = args.user
                 mSelf:userInit()
            elseif args.cmd ==1 then
            
            end
        end
    end

    socketEvent.ongameready=function (args)
        player.gameStart=true
        self.quiteBtn:setButtonLabel(cc.ui.UILabel.new({text = "退出"}))
        mSelf.playFlag = false
        mSelf:palyerInit(args.index)
        mSelf:cards(args)
        if args.index == mSelf.index then
             self.gameStartBtn:removeSelf()
             self.takeBtn:setVisible(true)
             self.takeBtn:setButtonLabel(cc.ui.UILabel.new({text = "出牌"}))
             self.playFlag=true
        end
        mSelf:master(args.master)
        mSelf:clockShow(args.index,nil,false)
    end

    socketEvent.takecard = function(args)
    print("拿到牌了",args.card)
        if args.ok == 1 then
            mSelf:take(args.card)
        elseif args.ok == -3 then
            print("没牌了")
        end
    end

    socketEvent.onplay = function(args)
    -- dump(args)
        if args.ok == 0 then
            mSelf:onplay(args.card,args.index)
        end
    end

    socketEvent.playcommand = function(args)
        if args.ok == 1 then
            local index = mSelf.index + 1 
            if index == 4 then
                index =1
            end
           mSelf:clockShow(index,nil,false)
        end
    end

    self.takeBtn = cc.ui.UIPushButton.new("Button01.png", {scale9 = true})
    self.takeBtn:setButtonSize(100, 40)
    :setButtonLabel(cc.ui.UILabel.new({text = "出牌"}))
    :onButtonPressed(function(event)
        event.target:setScale(1.1)
    end)
    :onButtonRelease(function(event)
        event.target:setScale(1.0)
    end)
    :onButtonClicked(function()
        if self.playFlag then
          self:play()
       end
    end)
    :pos(display.width-120, display.cy-100)
    :addTo(self)
    self.takeBtn:setVisible(false)

    self.pengBtn = cc.ui.UIPushButton.new("Button01.png", {scale9 = true})
    self.pengBtn:setButtonSize(100, 40)
    :setButtonLabel(cc.ui.UILabel.new({text = "碰"}))
    :onButtonPressed(function(event)
        event.target:setScale(1.1)
    end)
    :onButtonRelease(function(event)
        event.target:setScale(1.0)
    end)
    :onButtonClicked(function()
          if  mSelf.penCmd ==1 then
            self:peng()
            elseif mSelf.penCmd ==2 then
              self:hu()
            end
    end)
    :pos(display.width-250, display.cy-100)
    :addTo(self)
    self.pengBtn:setVisible(false)

    self.pengNoBtn = cc.ui.UIPushButton.new("Button01.png", {scale9 = true})
    self.pengNoBtn:setButtonSize(100, 40)
    :setButtonLabel(cc.ui.UILabel.new({text = "不碰"}))
    :onButtonPressed(function(event)
        event.target:setScale(1.1)
    end)
    :onButtonRelease(function(event)
        event.target:setScale(1.0)
    end)
    :onButtonClicked(function()
          if  mSelf.penCmd ==1 then
            self:pengNo()
            elseif mSelf.penCmd ==2 then
              self:huNo()
            end
    end)
    :pos(display.width-120, display.cy-100)
    :addTo(self)
    self.pengNoBtn:setVisible(false)


    mSelf=self
    mSelf.userid = args.userid
    if not args.user then
      args.user = {{userid = mSelf.userid }}
    end
    mSelf.user = args.user
    mSelf.roomid= args.roomid
    mSelf:userInit()
    self.quiteBtn= cc.ui.UIPushButton.new("btn_orange.png", {scale9 = true})
    :setButtonSize(80, 40)
    :setButtonLabel(cc.ui.UILabel.new({text = "离开"}))
    :onButtonPressed(function(event)
        event.target:setScale(1.1)
    end)
    :onButtonRelease(function(event)
        event.target:setScale(1.0)
    end)
    :onButtonClicked(function()
          self:exit()
    end)
    :pos(display.width-50, display.height-50)
    :addTo(self)

  --TODO 演示下初始牌
    -- local args = {index=1,cards="29,1,2,3,4,5,6,7,8,9,9,13,13,13,15,16,16,17,17,19,19,19"}
    -- mSelf:palyerInit(args.index)
    -- mSelf:cards(args)
    -- player.right={}
    --     player.left={}
    -- mSelf:onplay(13,3)

end

function TableView:gameStart()
 self.gameStartBtn = cc.ui.UIPushButton.new("btn_orange.png", {scale9 = true})
    self.gameStartBtn:setButtonSize(120, 40)
    :setButtonLabel(cc.ui.UILabel.new({text = "开始游戏"}))
    :onButtonPressed(function(event)
        event.target:setScale(1.1)
    end)
    :onButtonRelease(function(event)
        event.target:setScale(1.0)
    end)
    :onButtonClicked(function()
         socketEvent.request("gameready")
    end)
    :pos(display.width-120, display.cy-120)
    :addTo(self)
end

function TableView:master(cards)
     local begin =200

  cc.ui.UILabel.new({
  UILabelType = 2, text = "将牌:", font="fonts/fzcyt.ttf",size = 20})
       :align(display.CENTER, begin+20, display.height-20)
        :setColor(cc.c3b(247, 14, 107))
       :addTo(self)

   for c in string.gmatch(cards, "%d+") do
        local frames = display.newFrames(c..".png", 1, 1);
        local sprite = display.newSprite(frames[1])
        sprite:setAnchorPoint(0,0)
        sprite:setPosition(begin, display.height-sprite:getContentSize().height/2-40)
        sprite:setScale(0.5)
        begin = begin +50
        self:addChild(sprite);
   end
end

function TableView:cards(args)

   self.cardList = {}
   local begin =(display.width-cardnum*30)/2
    for c in string.gmatch(args.cards, "%d+") do
        local frames = display.newFrames(c..".png", 1, 1);
        local sprite = display.newSprite(frames[1])
        local card = {}
        card.play = false
        card.sprite=sprite
        card.card = tonumber(c)
        table.insert(self.cardList,card)
        sprite:setAnchorPoint(0,0)
        sprite:setPosition(begin, 60)
        sprite:setScale(0.5)
        sprite:setTouchEnabled(true) 
        sprite:setTouchMode(cc.TOUCHES_ALL_AT_ONCE)
        sprite:addNodeEventListener(cc.NODE_TOUCH_EVENT, function (event)
          if event.name == "began" and self.playFlag then
             self:back(sprite)
          local x,y = sprite:getPosition()
          if not card.play then
              card.play = true
              y = y + 40 
          else
              card.play = false
              y = y - 40
          end
          transition.moveTo(sprite, {time = 0.2, x = x, y = y})
        end
         return true
    end)
        self:addChild(sprite);
        begin = begin +30
    end
end

function TableView:clock(textL,waitPeng)
  -- print(textL:getText())
  TableView.clockCount = TableView.clockCount - 1
  if waitPeng then
    if TableView.clockCount < 10 then
      textL:setColor(cc.c3b(247, 14, 107))
    end
    textL:setString(TableView.clockCount)
    if  TableView.clockCount == 0 and mSelf.playFlag then
         mSelf:play()
    end
  else
      textL:setColor(cc.c3b(247, 14, 107))
      textL:setString(TableView.clockCount)
      if  TableView.clockCount == 0 then
         if mSelf.clockId then
            Timer:kill(mSelf.clockId)
         end
      end
  end
end

function TableView:userInit()
    if not mSelf.index then
      local index = 1
      for i,v in ipairs(mSelf.user) do
          if v.userid == mSelf.userid then
              index= i
              break
          end
      end
      mSelf.index = index
  end
  local rightIndex = mSelf.index +1
    if rightIndex ==4 then
        rightIndex = 1
    end
    local leftIndex = rightIndex+1
     if leftIndex ==4 then
        leftIndex = 1
    end
    print(leftIndex,rightIndex,"==========")

  if not player.left and  mSelf.user[leftIndex] then
     player.left = mSelf.user[leftIndex]
     player.left.index =leftIndex
     player.left.clock = {x=120+30,y=display.cy-30}
       cc.ui.UILabel.new({
           UILabelType = 2, text = player.left.name, size = 20})
          :align(display.CENTER, 60, display.cy+(40+20)/2-100)
          :setColor(cc.c3b(247, 14, 107))
          :addTo(self)
     local av = "player.png"
     if bankerIndex == leftIndex then
        av = "banker.png"
     end
     cc.ui.UIImage.new(av)
        :align(display.CENTER, 40, display.cy+40)
        :addTo(self)
  end 

  if not player.right and mSelf.user[rightIndex] then
     player.right = mSelf.user[rightIndex]
     player.right.index =rightIndex
     player.right.clock = {x=display.width-(120+30),y=display.cy-30}
     cc.ui.UILabel.new({
           UILabelType = 2, text = player.right.name, size = 20})
        :align(display.CENTER, display.width-60, display.cy+(40+20)/2-100)
        :setColor(cc.c3b(247, 14, 107))
        :addTo(self)
      av = "player.png"
     if bankerIndex == rightIndex then
        av = "banker.png"
     end
    cc.ui.UIImage.new(av)
        :align(display.CENTER, display.width-50, display.cy+40)
        :setScaleX(-1)
        :addTo(self)
  end 
  if not player.center then
    local av = "player.png"
       if 1 == mSelf.index then
          av = "banker.png"
       end
       cc.ui.UIImage.new(av)
          :align(display.CENTER, 40, 66)
          :addTo(self)
        player.center={}
       player.center.clock = {x=80,y=120}
  end
end

function TableView:palyerInit(bankerIndex,clock)
    clock = clock or 60
    local textL = cc.ui.UILabel.new({
           UILabelType = 2, text = tostring(clock), size = 20})
    textL:align(display.CENTER, 60/2, (60-10)/2)
    :setColor(cc.c3b(51, 51, 51))
    mSelf.spriteLabel= textL

    -- self.clock 
    mSelf.spriteClock = display.newSprite("clock.png")
    mSelf.spriteClock:setAnchorPoint(0,0)
    :addTo(self)
    :addChild(textL)

end

local function canHu(cardList)
  local cardArray = {}
  for i,v in ipairs(cardList) do
    table.insert(cardArray,v.card)
  end
   flag,data = cprule.huCheck(cardArray)
   if flag then
     mSelf.pengNoBtn:setVisible(true)
     mSelf.pengNoBtn:setButtonLabel(cc.ui.UILabel.new({text = "不胡"}))
     mSelf.pengBtn:setVisible(true) 
     mSelf.pengNoBtn:setButtonLabel(cc.ui.UILabel.new({text = "胡"}))
     self.penCmd = 2
   end
end

function TableView:take(c)
  local newCard = {}
  newCard.play = false
  newCard.card = c

  local i = 0
  while i+1 <=#self.cardList do
    -- print(self.cardList[i].card,":card")
    if newCard.card < self.cardList[i+1].card then
        break
    end
    i = i+1
  end

  i = i+1
  print(i,":pos take")
  local x,y
  local insertI = i
  if i == #self.cardList+1 then
     local lastCard = self.cardList[i-1]
      x,y = lastCard.sprite:getPosition()
      x = x + 30
  else
     local lastCard = self.cardList[i]
     if lastCard == nil then
        print(i,"----------isnull-------------",card)
     end
      x,y = lastCard.sprite:getPosition()
  end
  
  local frames = display.newFrames(c..".png", 1, 1);
  local sprite = display.newSprite(frames[1])

  while i<=#self.cardList do
       local card =self.cardList[i]
       local x,y = card.sprite:getPosition()
       transition.moveTo(card.sprite, {time = 0.2, x = x + 30, y = y})
       i = i + 1
    end


  newCard.play = true
   sprite:setAnchorPoint(0,0)
        sprite:setPosition(x, y+40)
        sprite:setScale(0.5)
        sprite:setTouchEnabled(true) 
        sprite:setTouchMode(cc.TOUCHES_ALL_AT_ONCE)
        sprite:addNodeEventListener(cc.NODE_TOUCH_EVENT, function (event)
         if event.name == "began" and self.playFlag then
                  self:back(sprite)
                  local x,y = sprite:getPosition()
                  if not newCard.play then
                      newCard.play = true
                      y = y + 40 
                  else
                      newCard.play = false
                      y = y - 40
                  end
                  transition.moveTo(sprite, {time = 0.2, x = x, y = y})
                 return true
               end
            end)
    self:addChild(sprite);
    self.takeBtn:setButtonLabel(cc.ui.UILabel.new({text = "出牌"}))
    self.playFlag = true
    newCard.sprite=sprite

    table.insert(self.cardList,insertI,newCard)
    transition.moveTo(sprite, {time = 0.2, x = x, y = 60+40})
    canHu(self.cardList)
end

function TableView:play(mcard)
  local pos = 0
  if not mcard then
  for i,v in ipairs(self.cardList) do
    if v.play then
      pos = i
      break
    end
  end
else
for i,v in ipairs(self.cardList) do
    if v.card == mcard then
      pos = i
      break
    end
  end
end
print("pos",pos,"--------")
  if pos > 0 then
    if self.lastSprite  then
        self.lastSprite:removeSelf()
        self.lastSprite=nil
    end
   local card =self.cardList[pos]
   self.lastSprite = card.sprite
  local x,y = card.sprite:getPosition()
  transition.moveTo(card.sprite, {time = 0.2, x = display.cx-card.sprite:getContentSize().width/4, y = display.cy-card.sprite:getContentSize().height/4})
  table.remove(self.cardList,pos)
  if not mcard then
    socketEvent.request("playcommand",{cmd=0,index=mSelf.index,card=card.card})
  end

  local key=tostring(card.card)
  audio.playSound(EFFECT[key], false)
  -- pos = pos +1
    while pos<=#self.cardList do
       card =self.cardList[pos]
       x,y = card.sprite:getPosition()
       transition.moveTo(card.sprite, {time = 0.2, x = x - 30, y = y})
       pos = pos + 1
    end
    self.playFlag = false
    self.takeBtn:setVisible(false)
  end
end

local function canPen(cardList,card)
  local cardArray = {}
  for i,v in ipairs(cardList) do
    table.insert(cardArray,v.card)
  end
  return cprule.pengCheck(cardArray,card)
end

function TableView:onplay(card,index,waitPeng)
  print("出牌了，",card,index)

   local key=tostring(card)
   audio.playSound(EFFECT[key], false)

    if self.lastSprite  then
       self.lastSprite:removeSelf()
       self.lastSprite=nil
    end
    local frames = display.newFrames(card..".png", 1, 1);
    self.lastSprite = display.newSprite(frames[1])
    self.lastSprite:setAnchorPoint(0,0)
    self.lastSprite:setScale(0.5)
    if player.right.index == index then 
        self.lastSprite:setPosition(display.width-40,display.cy)
    else
        self.lastSprite:setPosition(40,display.cy)
    end
     self:addChild(self.lastSprite);
     transition.moveTo(self.lastSprite, {time = 0.2, x = display.cx-self.lastSprite:getContentSize().width/4, y = display.cy-self.lastSprite:getContentSize().height/4})
     index = index +1
     if index == 4 then
        index = 1
     end
      if waitPeng ~= 1 then
         socketEvent.request("takecard",{index=mSelf.index})
         self.takeBtn:setVisible(true)
      else
         mSelf:clockShow(index,nil,false)
      end
     -- if index == mSelf.index then
     --  if canPen(self.cardList,card) then
     --         mSelf.pengNoBtn:setVisible(true)
     --         mSelf.pengNoBtn:setButtonLabel(cc.ui.UILabel.new({text = "不碰"}))
     --         mSelf.pengBtn:setVisible(true) 
     --         mSelf.pengBtn:setButtonLabel(cc.ui.UILabel.new({text = "碰"}))
     --         self.penCmd = 1
     --         mSelf.pengCard = card
     --   else
     --     socketEvent.request("takecard",{index=mSelf.index})
     --     self.takeBtn:setVisible(true)
     --    end
     -- end
end

function TableView:waitpeng(args)
   if args.index == mSelf.index then
       mSelf.pengNoBtn:setVisible(true)
       mSelf.pengNoBtn:setButtonLabel(cc.ui.UILabel.new({text = "不碰"}))
       mSelf.pengBtn:setVisible(true) 
       mSelf.pengBtn:setButtonLabel(cc.ui.UILabel.new({text = "碰"}))
       self.penCmd = 1
       mSelf.pengCard = card
   else
      -- 5s闹钟
       self:clockShow(args.index,5,true)
   end
end

function TableView:back(sprite)
  for i,v in ipairs(self.cardList) do
    if not sprite then
      if  v.play then
          v.play = false
         local x,y = v.sprite:getPosition()
        transition.moveTo(v.sprite, {time = 0.2, x = x, y = y-40})
    end
    else
      if  v.play and  v.sprite ~= sprite then
          v.play = false
          local x,y = v.sprite:getPosition()
          transition.moveTo(v.sprite, {time = 0.2, x = x, y = y-40})
    end
    end
  end
end

function TableView:clockShow(index,second,peng)
    print("-------clock index:",index,second)
    mSelf.playindex = index

    if mSelf.clockId then
        Timer:kill(mSelf.clockId)
    end
    if player.right.index == index then 
        mSelf.spriteClock:setPosition(player.right.clock.x,player.right.clock.y)
    elseif player.left.index == index then 
        mSelf.spriteClock:setPosition(player.left.clock.x,player.left.clock.y)
    else
        mSelf.spriteClock:setPosition(player.center.clock.x,player.center.clock.y)
    end
    local clock = 60
    if second and second~=nil then
      clock=second
    end
    -- print(clock,"-----clock",Timer,self.clock,mSelf.spriteLabel)
    TableView.clockCount = clock
    mSelf.clockId = Timer:start(self.clock,1,clock,mSelf.spriteLabel,peng)
end

function TableView:exit()

    -- device.showAlert("提示", "是否确定退出 ?", {"确定", "取消"}, function(event)
    --     if event.buttonIndex == 1 then
          if player.gameStart then
              socketEvent.request("roomcommand",{id=mSelf.roomid,cmd=2})
          else
            --直接退出，游戏结束
              socketEvent.request("roomcommand",{id=mSelf.roomid,cmd=1})
          end

    --    end
    -- end)

end

function TableView:onaiplay(args)
  local card = args.card
   self:back()
   -- self:takecard(card)
  self:play(card)

   local index = mSelf.index + 1 
            if index == 4 then
                index =1
            end
    mSelf:clockShow(index,nil,false)
end

function TableView:onclock(args)
    --second,index
    local second = args.clock
    if second >0 then
      local playindex = args.index
      mSelf:clockShow(playindex,second,false)
    end
end

function TableView:peng()
    socketEvent.request("peng",{index=mSelf.index,card=mSelf.pengCard})
  -- self:onpeng({index=mSelf.index})
end

function TableView:pengNo()
  print("------不peng------")
  self.pengNoBtn:setVisible(false)
  self.pengBtn:setVisible(false)
  socketEvent.request("takecard",{index=mSelf.index})
  self.playFlag = true
  self.takeBtn:setVisible(true)
  mSelf.pengCard = nil

end

function TableView:onpeng(args)
 if args.index == mSelf.index then
    --添加到碰的区域
    if self.lastSprite  then
       self.lastSprite:removeSelf()
       self.lastSprite=nil
    end
    --删除自己碰的牌
    local index = #self.cardList
    local count = 0
    while index > 0 do
      if self.cardList[index].card == mSelf.pengCard then
          self.cardList[index].sprite:removeSelf()
          table.remove(self.cardList,index)
          print("------remove------",self.cardList[index].card)
          count = count + 1
          if count == 3 then
              -- index=index-1
              if index == 0 then
                index = 1
              end
            break
          end
      end
      index=index-1
    end
    index = index + 1
    if index ~= #self.cardList then
      while index <= #self.cardList do
         local card =self.cardList[index]
          local x,y = card.sprite:getPosition()
          transition.moveTo(card.sprite, {time = 0.2, x = x - 30*4, y = y})
         index = index + 1
      end
    end 
    --插入到碰列表
    if not self.penList then
      self.penList = {}
    end
    table.insert(self.penList,mSelf.pengCard)
    local start = 100

    local frames = display.newFrames(mSelf.pengCard ..".png", 1, 1);
    local sprite = display.newSprite(frames[1])
    sprite:setAnchorPoint(0,0)
    local delay = (#self.penList-1)*40

    sprite:setPosition(display.cx-sprite:getContentSize().width/4, display.cy-sprite:getContentSize().height/4)

    -- sprite:setPosition(start+sprite:getContentSize().height/2+delay, sprite:getContentSize().width-40)
    sprite:setScale(0.5):setRotation(-90)
    self:addChild(sprite);

    transition.moveTo(sprite, {time = 0.2, x = start+sprite:getContentSize().height/2+delay, y =  sprite:getContentSize().width-40})

    mSelf.pengCard = nil

    print("------碰完去抓牌------")
    socketEvent.request("takecard",{index=mSelf.index})
    self.takeBtn:setVisible(true)
    -- mSelf.pengNoBtn:setVisible(false)
    -- mSelf.pengBtn:setVisible(false)
    -- self.takeBtn:setVisible(true)
    -- self.playFlag = true


 else
    --别人碰了
    if self.lastSprite  then
       self.lastSprite:removeSelf()
       self.lastSprite=nil
    end
 end
 --TODO 播放碰的动画
end


function TableView:hu()
    mSelf.pengNoBtn:setVisible(false)
    mSelf.pengBtn:setVisible(false)
    socketEvent.request("hu",{index=mSelf.index})
end

function TableView:huNo()
   self.pengNoBtn:setVisible(false)
   self.pengBtn:setVisible(false)
   self.takeBtn:setVisible(true)
   self.playFlag = true
end

function TableView:roominfo(resp)
        player.gameStart=true
        mSelf.playFlag = false
        mSelf:palyerInit(resp.index,resp.clock)
        mSelf:cards(resp)
        mSelf:onclock(resp)
        self.quiteBtn:setButtonLabel(cc.ui.UILabel.new({text = "退出"}))
        if resp.index == mSelf.index then
             -- self.gameStartBtn:removeSelf()
             self.takeBtn:setVisible(true)
             self.takeBtn:setButtonLabel(cc.ui.UILabel.new({text = "出牌"}))
             self.playFlag=true
        end
        mSelf:master(resp.master)
        -- mSelf:clockShow(resp.index)
end

-- function TableView:hu(args)
--   --args.index 胡了
-- end

return TableView